package com.github.h4de5ing.kmp
import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.fazecast.jSerialComm.SerialPort
import com.github.h4de5ing.kmp.rtk.*
import java.io.File

@Composable
@Preview
fun App() {
    MaterialTheme {
        var log by remember { mutableStateOf("") }
        val scrollState = rememberScrollState()
        var ip by remember { mutableStateOf("") }
        var port by remember { mutableStateOf("") }
        var mountPoint by remember { mutableStateOf("") }
        var username by remember { mutableStateOf("") }
        var password by remember { mutableStateOf("") }
        var isRtk by remember { mutableStateOf(false) }
        var isRadio by remember { mutableStateOf(false) }
        var text by remember { mutableStateOf("经度：\n纬度：\n卫星个数：\n状态：\n更新时间：") }
        var tips by remember { mutableStateOf("") }
        var configFinish by remember { mutableStateOf(false) }
        var showDialog by remember { mutableStateOf(false) }
        fun log(message: String) {
            log = "${log}${message}\n"
        }

        LaunchedEffect(Unit) {
            println("${os()}[${osArch()}]")
            SerialPort.getCommPorts().toList().forEach {
                if (it.portDescription == "CP2102 USB to UART Bridge Controller") {
                    radioUartName = it.systemPortName
                }
                println("${it.portDescription},${it.systemPortName}")
            }
            val file = File(System.getProperty("user.dir") + File.separator + "config.properties")
            if (!file.exists()) PUtils::class.java.classLoader.getResourceAsStream("config.properties")?.is2File(file)
            val p = PUtils.instance?.load("config.properties")
            ip = p?.get("ip") ?: ""
            port = p?.get("port") ?: ""
            mountPoint = p?.get("mountPoint") ?: ""
            username = p?.get("username") ?: ""
            password = p?.get("password") ?: ""
            isRtk = p?.get("isRtk").toBoolean()
            isRadio = p?.get("isRadio").toBoolean()
            tips = if (isRadio) if (isRtk) "RTK" else "基站" else "高精度定位模式"
            RTKApp(log = { log(it) }, onChange = {
                text =
                    "经度：${it.longitude}\n纬度：${it.latitude}\n卫星个数：${it.satellites}\n状态：${it.state}\n更新时间：${now()}"
            }).start(ip, 8002, mountPoint, username, password, isRadio, isRtk) {
                configFinish = true
            }
        }
        LaunchedEffect(log) { scrollState.scrollTo(scrollState.maxValue) }
        if (showDialog) AlertDialogExample(onConfirmation = { showDialog = false }, onChange = {
            changUIString = it
        })
        Column(modifier = Modifier.fillMaxSize().padding(5.dp)) {
            Box(modifier = Modifier.fillMaxWidth().weight(6f)) {
                Column {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween,
                    ) {
                        Text(
                            text = tips, textAlign = TextAlign.Center, fontWeight = FontWeight.Bold
                        )
                        if (configFinish)
                            TextButton(
                                shape = RoundedCornerShape(50),
                                contentPadding = PaddingValues(vertical = 3.dp),
                                onClick = { showDialog = !showDialog },
                            ) { Text(text = "电台配置", fontSize = 12.sp, color = Color.Black) }
                    }
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween,
                    ) {
                        Text("运行日志:", fontSize = 12.sp)
                        TextButton(
                            modifier = Modifier.size(40.dp, 30.dp),
                            shape = RoundedCornerShape(50),
                            contentPadding = PaddingValues(vertical = 3.dp),
                            onClick = { log = "" },
                        ) { Text(text = "清空", fontSize = 12.sp, color = Color.Black) }
                    }
                    OutlinedTextField(
                        value = log,
                        onValueChange = { log = it },
                        modifier = Modifier.fillMaxSize().verticalScroll(scrollState),
                        textStyle = LocalTextStyle.current,
                    )
                }
            }
            Box(
                modifier = Modifier.fillMaxWidth().weight(4f)
            ) {
                Row(modifier = Modifier.fillMaxSize()) {
                    Column(
                        modifier = Modifier.fillMaxSize().weight(5f)
                            .border(width = 1.dp, color = Color.LightGray, shape = RoundedCornerShape(3))
                    ) {
                        Column(modifier = Modifier.padding(10.dp)) {
                            Text(text = "ip=${ip}")
                            Text(text = "port=${port}")
                            Text(text = "mountPoint=${mountPoint}")
                            Text(text = "username=${username}")
                            Text(text = "password=${password}")
                            Spacer(modifier = Modifier.height(10.dp))
                            Text(text = "isRadio=${isRadio}")
                            Text(text = "isRtk=${isRtk}")
                        }
                    }
                    Column(
                        modifier = Modifier.fillMaxSize().weight(5f)
                            .border(width = 1.dp, color = Color.LightGray, shape = RoundedCornerShape(3))
                    ) {
                        Text(text = text, modifier = Modifier.padding(10.dp))
                    }
                }
            }
        }
    }
}